package com.fcgzs.order.service.impl;

import com.fcgzs.entity.Result;
import com.fcgzs.order.group.Cart;
import com.fcgzs.order.pojo.OrderItem;
import com.fcgzs.order.service.CartService;
import com.fcgzs.sellergoods.feign.ItemFeign;
import com.fcgzs.sellergoods.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: ljj
 * @Description:
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private ItemFeign itemFeign;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加购物车
     *
     * @param srcCartList 原有购物车集合
     * @param itemId      SKU的ID
     * @param num         购买数量
     * @return
     */
    @Override
    public List<Cart> addGoodsToCartList(List<Cart> srcCartList, Long itemId, Integer num) {
        //1.根据SKU的ID查询商品详情
        Result<Item> result = itemFeign.findById(itemId);
        Item item = result.getData();
        if(item==null){
            throw new RuntimeException("该商品不存在");
        }
        if(!item.getStatus().equals("1")){
            throw new RuntimeException("该商品状态非法");
        }
        String sellerId = item.getSellerId();     //商家ID
        String sellerName = item.getSeller();      //商家名称
        //2.判断sellerId在购物车列表中是否存在
        Cart cart = this.searchCartBySellerId(srcCartList,sellerId);
        if(cart==null){    //3.如果没有该购物车，则需要重新创建
            cart = new Cart();
            cart.setSellerId(sellerId);
            cart.setSellerName(sellerName);
            OrderItem orderItem = this.setOrderItem(item,num);
            List<OrderItem> orderItemList = new ArrayList<>();
            orderItemList.add(orderItem);
            cart.setOrderItemList(orderItemList);
            srcCartList.add(cart);   //将新创建的购物车重新放入到原购物车列表中

        }else{
            //4.判断购物车对象中是否有该商品
            OrderItem orderItem = this.searchOrderItemByItemId(cart,itemId);
            if(orderItem==null){   //如果没有改商品，则直接创建
                orderItem = this.setOrderItem(item,num);
                cart.getOrderItemList().add(orderItem);
            }else{  //否则，应该修改购买数量
                orderItem.setNum(orderItem.getNum()+num);    //重新修改购买数量
                orderItem.setTotalFee(orderItem.getPrice().multiply(new BigDecimal(orderItem.getNum())));    //重新计算总价格

                //判断订单详情的数量是否小于1，如果小于1，则移除改商品
                if(orderItem.getNum()==0){
                    cart.getOrderItemList().remove(orderItem);
                }

                //判断购物车的订单详情的集合元素数量如果为零，则在原购物列表中移除购物车对象
                if(cart.getOrderItemList().size()==0){
                    srcCartList.remove(cart);
                }
            }
        }
        return srcCartList;
    }

    @Override
    public List<Cart> findCartListFromRedis(String userId) {
      List<Cart> cartList = (List<Cart>)  redisTemplate.boundHashOps("cartList").get(userId);
      if(cartList==null){
          cartList = new ArrayList<>();
      }
      return cartList;
    }

    @Override
    public void saveCartListToRedis(List<Cart> cartList, String userId) {
        redisTemplate.boundHashOps("cartList").put(userId,cartList);
    }


    private Cart searchCartBySellerId(List<Cart> cartList,String sellerId){
        for (Cart cart : cartList) {
            if (cart.getSellerId().equals(sellerId)) {
                return cart;
            }
        }
        return null;
    }

    private OrderItem setOrderItem(Item item,Integer num){
        if(num<1){
            throw new RuntimeException("购买数量不合法");
        }

        //创建订单详情对象
        OrderItem orderItem = new OrderItem();
        orderItem.setItemId(item.getId());         //商品ID
        orderItem.setGoodsId(item.getGoodsId());    //SPU的ID
        orderItem.setTitle(item.getTitle());        //商品标题
        orderItem.setPrice(item.getPrice());       //商品单价
        orderItem.setNum(num);                    //购买数量
        orderItem.setTotalFee(orderItem.getPrice().multiply(new BigDecimal(num)));   //总金额
        orderItem.setPicPath(item.getImage());      //图片地址
        orderItem.setSellerId(item.getSellerId());   //商家ID
        return orderItem;
    }


    private OrderItem searchOrderItemByItemId(Cart cart,Long itemId){
        for (OrderItem orderItem : cart.getOrderItemList()) {
            if (orderItem.getItemId().longValue() == itemId.longValue()) {
                return orderItem;
            }
        }
        return null;
    }
}
